"""
音频控制模块 - 处理音频播放和音量控制
"""
import pygame
import os
from pathlib import Path

try:
    from ctypes import cast, POINTER
    from comtypes import CLSCTX_ALL
    from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
    AUDIO_AVAILABLE = True
except ImportError:
    AUDIO_AVAILABLE = False
    print("警告: 音频控制库不可用")


class AudioController:
    def __init__(self, ringtones_dir="ringtones"):
        """初始化音频控制器"""
        self.ringtones_dir = ringtones_dir
        self.original_volume = None
        
        # 初始化pygame mixer
        pygame.mixer.init()
        
        # 创建铃声目录
        os.makedirs(self.ringtones_dir, exist_ok=True)
    
    def get_available_ringtones(self):
        """获取可用的铃声列表"""
        audio_extensions = ['.mp3', '.wav', '.ogg']
        ringtones = []
        
        if os.path.exists(self.ringtones_dir):
            for file in os.listdir(self.ringtones_dir):
                if any(file.lower().endswith(ext) for ext in audio_extensions):
                    ringtones.append(file)
        
        return sorted(ringtones)
    
    def play_ringtone(self, ringtone_name, volume_percent, loop=True):
        """播放铃声"""
        try:
            file_path = os.path.join(self.ringtones_dir, ringtone_name)
            
            if not os.path.exists(file_path):
                raise FileNotFoundError(f"铃声文件不存在: {file_path}")
            
            pygame.mixer.music.load(file_path)
            pygame.mixer.music.set_volume(volume_percent / 100.0)
            
            if loop:
                pygame.mixer.music.play(-1)  # 无限循环
            else:
                pygame.mixer.music.play()
            
            return True
        except Exception as e:
            print(f"播放铃声失败: {e}")
            return False
    
    def stop_ringtone(self):
        """停止播放铃声"""
        try:
            pygame.mixer.music.stop()
        except Exception as e:
            print(f"停止播放失败: {e}")
    
    def is_playing(self):
        """检查是否正在播放"""
        return pygame.mixer.music.get_busy()
    
    def set_system_volume(self, volume_percent):
        """设置系统音量（仅Windows）"""
        if not AUDIO_AVAILABLE:
            print("音频控制不可用")
            return False
        
        try:
            devices = AudioUtilities.GetSpeakers()
            interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
            volume = cast(interface, POINTER(IAudioEndpointVolume))
            
            # 保存原始音量
            if self.original_volume is None:
                self.original_volume = volume.GetMasterVolumeLevelScalar()
            
            # 设置新音量
            volume.SetMasterVolumeLevelScalar(volume_percent / 100.0, None)
            return True
        except Exception as e:
            print(f"设置系统音量失败: {e}")
            return False
    
    def restore_system_volume(self):
        """恢复原始系统音量"""
        if not AUDIO_AVAILABLE or self.original_volume is None:
            return
        
        try:
            devices = AudioUtilities.GetSpeakers()
            interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
            volume = cast(interface, POINTER(IAudioEndpointVolume))
            volume.SetMasterVolumeLevelScalar(self.original_volume, None)
            self.original_volume = None
        except Exception as e:
            print(f"恢复系统音量失败: {e}")
    
    def get_system_volume(self):
        """获取当前系统音量"""
        if not AUDIO_AVAILABLE:
            return None
        
        try:
            devices = AudioUtilities.GetSpeakers()
            interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
            volume = cast(interface, POINTER(IAudioEndpointVolume))
            return int(volume.GetMasterVolumeLevelScalar() * 100)
        except Exception as e:
            print(f"获取系统音量失败: {e}")
            return None
    
    def add_ringtone(self, source_path):
        """添加新铃声到铃声库"""
        try:
            import shutil
            filename = os.path.basename(source_path)
            dest_path = os.path.join(self.ringtones_dir, filename)
            
            if os.path.exists(dest_path):
                # 如果文件已存在，添加数字后缀
                name, ext = os.path.splitext(filename)
                counter = 1
                while os.path.exists(dest_path):
                    filename = f"{name}_{counter}{ext}"
                    dest_path = os.path.join(self.ringtones_dir, filename)
                    counter += 1
            
            shutil.copy(source_path, dest_path)
            return filename
        except Exception as e:
            print(f"添加铃声失败: {e}")
            return None
    
    def delete_ringtone(self, ringtone_name):
        """删除铃声"""
        try:
            file_path = os.path.join(self.ringtones_dir, ringtone_name)
            if os.path.exists(file_path):
                os.remove(file_path)
                return True
            return False
        except Exception as e:
            print(f"删除铃声失败: {e}")
            return False
    
    def create_default_ringtone(self):
        """创建默认铃声"""
        try:
            # 尝试使用numpy和scipy创建默认铃声
            import numpy as np
            from scipy.io import wavfile
            
            sample_rate = 44100
            duration = 2.0
            
            # 创建一个简单的和弦
            t = np.linspace(0, duration, int(sample_rate * duration))
            frequencies = [440, 554, 659]  # A4, C#5, E5 (A大调和弦)
            
            wave = np.zeros_like(t)
            for freq in frequencies:
                wave += np.sin(2 * np.pi * freq * t) / len(frequencies)
            
            # 添加淡入淡出效果
            fade_samples = int(0.1 * sample_rate)
            wave[:fade_samples] *= np.linspace(0, 1, fade_samples)
            wave[-fade_samples:] *= np.linspace(1, 0, fade_samples)
            
            # 转换为16位整数
            wave = (wave * 32767 * 0.5).astype(np.int16)
            
            # 保存
            default_path = os.path.join(self.ringtones_dir, "默认铃声.wav")
            wavfile.write(default_path, sample_rate, wave)
            return True
        except ImportError:
            print("无法创建默认铃声 - 缺少numpy或scipy库")
            print("请手动添加MP3或WAV文件到ringtones文件夹")
            return False
        except Exception as e:
            print(f"创建默认铃声失败: {e}")
            return False
